package esb.chapter6.jdbc;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.jbi.JBIException;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.NormalizedMessage;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;

import org.apache.servicemix.components.util.DefaultFileMarshaler;

public class JDBCFileMarshaler extends DefaultFileMarshaler {

	public void readMessage(MessageExchange exchange,
			NormalizedMessage message, InputStream in, String path)
			throws IOException, JBIException {

		// don't use a streamsource as in the original one but directly create a
		// dom source. This is needed since the jdbc component transforms this stream
		// twice and thus causes errors.
		DOMResult result = new DOMResult();
		try {
			final TransformerFactory tFactory = TransformerFactory.newInstance();
			Transformer trans = tFactory.newTransformer();
			trans.transform(new StreamSource(in, path), result);
			trans = tFactory.newTransformer();
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		message.setContent(new DOMSource(result.getNode()));
		message.setProperty(FILE_NAME_PROPERTY, new File(path).getName());
		message.setProperty(FILE_PATH_PROPERTY, path);
	}
}
